package com.example.capturetheflag.connection;

import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import com.example.capturetheflag.joinGame.JoinMenuActivity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

public class HttpGetGamesRequest extends AsyncTask<String, Void, String> 
{
	private DefaultHttpClient defaultHttpClient;
	private HttpGet httpGetrequest;
	private HttpResponse httpResponse;
	private HttpEntity httpEntity;
	private String[] gamesTab;
	private Context context;
	private Dialog dialog;
	
	
	public HttpGetGamesRequest(Context context,Dialog dialog)	
	{
		this.dialog = dialog;
		this.context = context.getApplicationContext();
		defaultHttpClient = new DefaultHttpClient();
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
        Intent intent = new Intent(context, JoinMenuActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        
        Bundle bundle = new Bundle();
        bundle.putStringArray("games", gamesTab);
        intent.putExtras(bundle);
        
        dialog.dismiss();
        context.startActivity(intent);
	}	
		
	@Override
	protected String doInBackground(String... params) 
	{	
		httpGetrequest = new HttpGet(params[0]);
		httpGetrequest.setHeader("Accept", "application/json");
		httpGetrequest.setHeader("Content-type", "application/json");
		
		try
		{
		
		httpResponse = defaultHttpClient.execute(httpGetrequest);
		httpEntity = httpResponse.getEntity();
		
		 // Read response data into buffer
	      char[] buffer = new char[(int)httpEntity.getContentLength()];
	      InputStream stream = httpEntity.getContent();
	      InputStreamReader reader = new InputStreamReader(stream);
	      reader.read(buffer);
	      stream.close();
	      JSONArray jsonArray = new JSONArray(new String(buffer));
	      gamesTab = new String[jsonArray.length()];
	      for(int i=0;i<jsonArray.length();i++){
	    	  gamesTab[i] = jsonArray.getJSONObject(i).getString("name");
	      }
		}
		catch (Exception e) 
		{
			// TODO: handle exception
		}
		return null;
	}
}
